package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MenuService;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Reference
    private UserService userService;
    @Reference
    private MenuService menuService;


    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
        if (null == user || !user.getPassword().equals(param.getPassword())) {
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //用户信息写入 session
        request.getSession(true).setAttribute(CURRENT_USER, user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登出
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        log.info("[登出]……");
        //从session中删除用户
        request.getSession().removeAttribute(CURRENT_USER);
        //重定向到登录页
        response.sendRedirect("http://oms.health.itcast.com:8080/pages/login.html");
        return null;
    }


    /**
     * 获取当前登录用户名及当前用户菜单列表
     *
     * @return
     */
    @RequestMapping("/getUsernameAndMenu")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            //查询帐户
            User po = userService.findByUsername(user.getUsername());
            //查询账户对应的菜单
            //List<Menu> menus  =   MenuService.selectByUserId(po.getId());
            /*List<HashMap<String, Object>> menuLists = Arrays.asList(
                    new HashMap<String, Object>(){{
                        put("path","1");
                        put("title","体检1");
                        put("icon","heartbeat");
                        put("children",new ArrayList<>());
                    }},
                    new HashMap<String, Object>(){{
                        put("path","3");
                        put("title","体检2");
                        put("icon","heartbeat1");
                        put("children",new ArrayList<>());
                    }}
            );*/
            // rpc 远程获取 动态菜单



            List<Menu> menuLists = menuService.selectByUserId(po.getId());


            Map<String,Object> map = new HashMap<>();
            map.put("username",user.getUsername());
            map.put("menuList",menuLists);



            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, map);
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }

    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }



    //--------------------------------------------------------------------------------


    /**
     * 添加
     *
     * @return
     */
    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody User user, Integer[] roleIds) {
        log.info("[用户-添加]data:{},roleIds:{}", user, roleIds);
        //RPC请求添加
        userService.add(user,roleIds);
        return new Result(true, MessageConst.ADD_SUCCESS);
    }


    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @GetMapping("/findPage")
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result findPage(QueryPageBean queryPageBean) {
        log.info("[用户-分页查询]data:{}", queryPageBean);
        //rpc查询结果
        PageResult pageResult = userService.pageQuery(queryPageBean);
        //构造返回对象
        return new Result(true,MessageConst.QUERY_SUCCESS,pageResult);

    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findById(Integer id) {
        log.info("[用户-根据id查询]id:{}", id);

        //rpc 调用业务处理
        User user =userService.findById(id);
        //封装返回值
        return new Result(true, MessageConst.QUERY_SUCCESS, user);

    }

    /**
     * 根据检查组ID查询关联的检查项ID集和
     *
     * @param id
     * @return
     */
    @RequestMapping("/findroleIdsByCheckUserId")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findroleIdsByCheckUserId(Integer id) {
        log.info("[用户-根据检查组ID查询关联的检查项ID集和]id:{}", id);

        //rpc 调用业务处理
        List<Integer> roleIds = userService.findroleIdsByCheckUserId(id);
        //封装返回值
        return new Result(true, MessageConst.QUERY_SUCCESS, roleIds);

    }

    /**
     * 编辑
     *
     * @return
     */
    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody User user, Integer[] roleIds) {
        log.info("[用户-编辑]data:{},roleIds:{}", user, roleIds);

        //RPC请求添加
        userService.edit(user, roleIds);
        return new Result(true, MessageConst.UPDATE_SUCCESS);

    }

    /**
     * 查询所有
     *
     * @return
     */
    @RequestMapping("/findAll")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findAll() {
        //rpc调用查询数据
        List<User> users = userService.findAll();
        //封装返回结果
        return new Result(true, MessageConst.QUERY_SUCCESS, users);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id){
        log.info("[角色-根据id删除]id：{}",id);
        //RPC调用处理业务
        userService.delete(id);
        return new Result(true,MessageConst.DELETE_SUCCESS);
    }




}
